<?php

/**
 * Created by PhpStorm.
 * Script Name: Mpsetting.php
 * Create: 2022/12/31 下午10:16
 * Description: 公众号相关设置
 * Author: fudaoji<fdj@kuryun.cn>
 */

namespace plugin\wechat\app\tenant\controller;

use app\common\service\Tenant as TenantService;
use plugin\wechat\app\TenantController;
use plugin\wechat\app\model\MpSetting as SettingM;
use Support\Request;
use plugin\wechat\app\service\Mp as MpService;

class Mpsetting extends TenantController
{

    /**
     * @var SettingM
     */
    protected $model;

    public function __construct()
    {
        parent::__construct(); // TODO: Change the autogenerated stub
        $this->model = new SettingM();

    }

    private static function tabList(){
        return [
            'wxpay' => [
                'title' => '微信支付',
                'href' => url('index', ['name' => 'wxpay'])
            ],
            'quota' => [
                'title' => '接口调用',
                'href' => url('quota', ['name' => 'quota'])
            ]
        ];
    }

    /**
     * 设置
     * @param Request $request
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author: fudaoji<fdj@kuryun.cn>
     */
    public function index(Request $request){
        $current_name = input('name', 'wxpay');
        $mp_info = $request->mpInfo;
        $where = [
            $this->tenantWhere(),
            ['mp_id','=', $mp_info['id']],
            ['name','=', $current_name]
        ];
        $setting = $this->model->where($where)
            ->find();
        if(request()->isPost()){
            $post_data = input('post.');
            unset($post_data['__token__']);
            if(empty($setting)){
                $res = $this->model->create([
                    'company_id' => TenantService::getCompanyId(),
                    'mp_id' => $mp_info['id'],
                    'name' => $current_name,
                    'title' => $this->tabList()[$current_name]['title'],
                    'value' => json_encode($post_data, JSON_UNESCAPED_UNICODE)
                ]);
            }else{
                $res = $this->model->update([
                    'id' => $setting['id'],
                    'value' => json_encode($post_data, JSON_UNESCAPED_UNICODE)
                ]);
            }
            if($res){
                return $this->success('操作成功！', url('index', ['name' => $current_name]));
            }else{
                return $this->error('操作失败！', '', ['token' => request()->token()]);
            }
        }

        if(empty($setting)){
            $data = [];
        }else{
            $data = json_decode($setting['value'], true);
        }
        $builder = new FormBuilder();
        switch ($current_name){
            case 'wxpay':
                $builder->addFormItem('appid', 'text', 'AppId', 'AppId', [], 'required maxlength=150')
                    ->addFormItem('mchid', 'text', '商户ID', '商户ID', [], 'required maxlength=100')
                    ->addFormItem('p_appid', 'text', '服务商AppId', '如果是服务商模式，需要填写此项', [], ' maxlength=150')
                    ->addFormItem('p_mchid', 'text', '服务商商户ID', '如果是服务商模式，需要填写此项', [], ' maxlength=100')
                    ->addFormItem('key', 'text', '支付秘钥', '支付秘钥', [], 'required maxlength=32 minlength=32')
                    ->addFormItem('cert_path', 'textarea', '支付证书cert', '请在微信商户后台下载支付证书，用记事本打开apiclient_cert.pem，并复制里面的内容粘贴到这里。', [], 'maxlength=20000')
                    ->addFormItem('key_path', 'textarea', '支付证书key', '请在微信商户后台下载支付证书，使用记事本打开apiclient_key.pem，并复制里面的内容粘贴到这里。', [], ' maxlength=20000')
                    ->addFormItem('rsa_path', 'textarea', 'RSA公钥', '企业付款到银行卡需要RSA公钥匙');
                break;
        }
        $builder->setTabNav($this->tabList(), $current_name)
            ->setFormData($data);
        return $builder->show();

    }

    /**
     * 接口调用情况
     * @param Request $request
     * @return mixed
     * Author: fudaoji<fdj@kuryun.cn>
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function quota(Request $request){
        if($request->isPost()){
            if($api = input('api', '')){
                if(is_string($res = MpService::quotaGet($api))){
                    return $this->error($res);
                }
                $html = "<p>当天该账号可调用该接口的次数: {$res['quota']['daily_limit']}</p>
<p>当天已经调用的次数: {$res['quota']['used']}</p><p>当天剩余调用次数: {$res['quota']['remain']}</p>";
                return $this->success('', '', $html);
            }else{
                if(is_string($res = MpService::quotaClear())){
                    return $this->error($res);
                }
                return $this->success('操作成功', '');
            }
        }
        $assign = [
            'tab_nav' => ['tab_list' => $this->tabList(), 'current_tab' => __FUNCTION__]
        ];
        return $this->show($assign);
    }
}